package com.fhz.a2102mvi.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.fhz.a2102mvi.datasource.MainRemoteDataSource
import com.fhz.a2102mvi.entity.Banner
import com.fhz.a2102mvi.entity.BannerEntity
import com.fhz.a2102mvi.intent.BannerIntent
import com.fhz.a2102mvi.repository.MainRepository
import com.fhz.a2102mvi.uistate.BannerUIState
import com.fhz.a2102mvi.utils.RetrofitFactory
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * 时间:2023/10/14
 * @author Mr.Feng
 * 简述: TODO
 */

@HiltViewModel
class MainViewModel @Inject constructor(val mainRepository:MainRepository) : ViewModel() {



    //两个协程之间的数据通信
    val channels = Channel<BannerIntent>(Channel.UNLIMITED)

    //liveData
    //Rxjava
    //flow
    private val _uiState = MutableStateFlow(BannerUIState.Success(null)) //viewmodel
    val uiState : StateFlow<BannerUIState>  = _uiState//activity

//    private val _a = mutableListOf<String>()
//    val a : List<String> = _a
//
    init {
        handlerIntent()
    }

   suspend fun insertBanner(bannerEntity: BannerEntity){
        mainRepository.insertBanner(bannerEntity)
    }

    private fun handlerIntent() {
        viewModelScope.launch {
            channels.consumeAsFlow().collect{
                when(it){
                    is BannerIntent.GetBannerList -> getBannerList()
                    is BannerIntent.ClickBanner -> clickBanner()
                }
            }
        }
    }

    //点击banner
    private  fun clickBanner() {
       //处理行为
        viewModelScope.launch {
            clickBanner1().collect{
                banner -> _uiState.value = BannerUIState.Success(banner)
            }
        }
    }

    private fun getBannerList() {
        viewModelScope.launch {
            banners().catch {
                e ->
                println("$e -----")
            }
                .collect{
                banner -> _uiState.value = BannerUIState.Success(banner)
            }


//            flow<Banner>{
//                val bannerList = repository.getBannerList(0,1,5)
//                emit(bannerList)
//            }.stateIn(initialValue = BannerUIState.Loading, scope = viewModelScope,
//                started = SharingStarted.WhileSubscribed(3000))
//              .collect{
////                  banner -> _uiState.value = BannerUIState.Success(banner)
//              }

        }
    }


    private fun banners(): Flow<Banner> = flow {
        val bannerList = mainRepository.getBannerList(0,1,5)
        println(bannerList.data.list.size)
        println("=====")
        emit(bannerList)
    }

    private fun clickBanner1(): Flow<Banner> = flow {
//        val bannerList = repository.clickBanner(0)
//        emit(bannerList)
    }

}